﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Data.SqlClient;

namespace BEELab
{
    public partial class PasswordRecovery : System.Web.UI.Page
    {
        /// <summary>
        /// Occures on every page load (first time or Post Back)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Occures when a user forgot his site's password.
        /// Function sends the user an email with a link that is used to reset his password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSignIn_Click(object sender, EventArgs e)
        {
            //If user doesn't exists on DB - return
            if (!BEELab.Logic.UserManagement.EmailRegistered(txtEmail.Text))
                return;

            string token = BEELab.Logic.UserManagement.CreateToken(txtEmail.Text);

            //Creates new email object to send to the user
            MailMessage message = new MailMessage();
            message.From = new MailAddress("beelab-noreply@bgu.ac.il");
            message.To.Add(new MailAddress(txtEmail.Text));
            message.Subject = "BEE Lab Password Recovery";
            message.IsBodyHtml = true;
            message.Body = "Please follow this link to reset your password: <a href=\"" + Request.Url.OriginalString.Substring(0, Request.Url.OriginalString.LastIndexOf('/')) + ResolveClientUrl("/ResetPassword.aspx?Token=") + token + "\">Password Reset</a>";
            message.Priority = MailPriority.High;
            SmtpClient mSmtpClient = new SmtpClient();
            mSmtpClient.Send(message);

            lblSent.Visible = true;
        }
    }
}